package com.whsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whsxt.domain.Basket;
import com.whsxt.domain.Sku;
import com.whsxt.feign.BasketSkuFeign;
import com.whsxt.mapper.BasketMapper;
import com.whsxt.service.BasketService;
import com.whsxt.vo.CartMoney;
import com.whsxt.vo.ShopCartItem;
import com.whsxt.vo.ShopCartResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-24 17:01
 * @Description: ${Description}
 */
@Service
@Slf4j
public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService {


    @Autowired
    private BasketMapper basketMapper;

    @Autowired
    private BasketSkuFeign basketSkuFeign;


    /**
     * 查询购物车商品数量
     *
     * @param openId
     * @return
     */
    @Override
    public Integer findCartCount(String openId) {
        //查询整个购物车
        List<Basket> basketList = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, openId)
        );
        //计算数量
        if (CollectionUtils.isEmpty(basketList)) {
            return 0;
        }
        Integer count = basketList.stream()
                .map(Basket::getBasketCount)
                .reduce(Integer::sum)
                .get();
        return count;
    }


    /**
     * 修改购物车商品数量
     * 1、购物车没有这个商品 就添加这个商品
     * 2、购物车有这个商品，修改数量+ -
     *
     * @param basket
     */
    @Override
    public void changeItem(Basket basket) {
        log.info("修改购物车商品数量：{}", basket);
        //查询购物车有没有这个商品
        Basket oldBasket = basketMapper.selectOne(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, basket.getUserId())
                .eq(Basket::getSkuId, basket.getSkuId())
        );

        if (oldBasket == null) {
            //新增
            basket.setBasketDate(new Date());
            basketMapper.insert(basket);
            return;
        }

        //修改数量
        int newCount = oldBasket.getBasketCount() + basket.getBasketCount();
        if (newCount < 0) {
            throw new RuntimeException("修改购物车数量不能小于0");
        }
        oldBasket.setBasketCount(newCount);
        oldBasket.setBasketDate(new Date());

        basketMapper.updateById(oldBasket);
    }


    /**
     * 查询购物车的详情
     * 1、查询basket表，拿到skuid
     * 2、根据skuid远程调用拿到sku的集合
     * 3、组装ShopCartItem数据返回
     *
     * @param openId
     * @return
     */
    @Override
    public List<ShopCartResult> getShopCartInfo(String openId) {
        List<Basket> basketList = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, openId)
        );

        if (CollectionUtils.isEmpty(basketList)) {
            return Collections.emptyList();
        }

        List<Long> skuIds = basketList.stream().map(Basket::getSkuId).collect(Collectors.toList());
        //远程调用商品模块
        List<Sku> skuList = basketSkuFeign.getSkuByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("服务器维护中，请稍后再试");
        }

        //组装数据
        List<ShopCartResult> shopCartResults = new ArrayList<>();
        ShopCartResult shopCartResult = new ShopCartResult();

        List<ShopCartItem> shopCartItems = new ArrayList<>();

        basketList.forEach(basket -> {
            ShopCartItem shopCartItem = new ShopCartItem();
            shopCartItem.setBasketId(basket.getBasketId());
            shopCartItem.setSkuId(basket.getSkuId());
            shopCartItem.setBasketCount(basket.getBasketCount());
            shopCartItem.setChecked(true);
            shopCartItem.setProdId(basket.getProdId());

            Sku sku = skuList.stream()
                    .filter(sku1 -> sku1.getSkuId().equals(basket.getSkuId()))
                    .collect(Collectors.toList())
                    .get(0);

            shopCartItem.setSkuName(sku.getSkuName());
            shopCartItem.setPrice(sku.getPrice().toString());
            shopCartItem.setProdName(sku.getProdName());
            shopCartItem.setPic(sku.getPic());
            shopCartItems.add(shopCartItem);
        });

        shopCartResult.setShopCartItems(shopCartItems);
        shopCartResults.add(shopCartResult);


        return shopCartResults;
    }


    /**
     * 计算购物车中选中商品的总金额
     *
     * @param basketIds
     * @return
     */
    @Override
    public CartMoney calcMoney(List<Long> basketIds) {
        //购物车  查到数量  然后查单价  在计算
        CartMoney cartMoney = new CartMoney();
        if (CollectionUtils.isEmpty(basketIds)) {
            return cartMoney;
        }

        List<Basket> basketList = basketMapper.selectBatchIds(basketIds); //这里只有数量
        List<Long> skuIds = basketList.stream()
                .map(Basket::getSkuId)
                .collect(Collectors.toList());
        //远程调用，拿到sku
        List<Sku> skuList = basketSkuFeign.getSkuByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("服务器维护中，请稍后再试");
        }
        //真实业务，查询用户有没有可用的优惠券，计算金额要带上
        List<BigDecimal> allMoney = new ArrayList<>();
        basketList.forEach(basket -> {
            Integer count = basket.getBasketCount();

            Sku sku1 = skuList.stream()
                    .filter(sku -> sku.getSkuId().equals(basket.getSkuId()))
                    .collect(Collectors.toList())
                    .get(0);
            BigDecimal price = sku1.getPrice();
            allMoney.add(price.multiply(new BigDecimal(count)));
        });

        BigDecimal totalMoney = allMoney.stream().reduce(BigDecimal::add).get();
        cartMoney.setTotalMoney(totalMoney);

        return cartMoney;
    }


    /**
     * 清空购物车
     *
     * @param openId
     * @param skuIds
     */
    @Override
    public void cleanCart(String openId, List<Long> skuIds) {
        basketMapper.delete(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, openId)
                .in(Basket::getSkuId,skuIds)
        );
    }
}
